package com.adk.backend.service.impl;

import com.adk.backend.entity.LxAdminFile;
import com.adk.backend.entity.LxAdminFlag;
import com.adk.backend.entity.LxAdminGroup;
import com.adk.backend.mapper.PermissionMapper;
import com.adk.backend.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限服务实现类
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public LxAdminGroup getGroupById(Integer groupId) {
        if (groupId == null || groupId <= 0) {
            return null;
        }
        return permissionMapper.selectGroupById(groupId);
    }
    
    @Override
    public List<LxAdminFile> getUserMenus(Integer userType) {
        if (userType == null || userType <= 0) {
            return Collections.emptyList();
        }
        
        LxAdminGroup group = getGroupById(userType);
        if (group == null || !StringUtils.hasText(group.getAllowFile())) {
            return Collections.emptyList();
        }
        
        // 解析允许的文件ID列表
        List<Integer> fileIds = parseIds(group.getAllowFile());
        if (fileIds.isEmpty()) {
            return Collections.emptyList();
        }
        
        return permissionMapper.selectFilesByIds(fileIds);
    }
    
    @Override
    public List<LxAdminFlag> getUserFlags(Integer userType) {
        if (userType == null || userType <= 0) {
            return Collections.emptyList();
        }
        
        LxAdminGroup group = getGroupById(userType);
        if (group == null || !StringUtils.hasText(group.getAllowFlag())) {
            return Collections.emptyList();
        }
        
        // 解析允许的权限ID列表
        List<Integer> flagIds = parseIds(group.getAllowFlag());
        if (flagIds.isEmpty()) {
            return Collections.emptyList();
        }
        
        return permissionMapper.selectFlagsByIds(flagIds);
    }
    
    @Override
    public Set<String> getUserFlagActs(Integer userType) {
        List<LxAdminFlag> flags = getUserFlags(userType);
        return flags.stream()
                .map(LxAdminFlag::getFlagAct)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }
    
    @Override
    public boolean hasPermission(Integer userType, String flagAct) {
        if (userType == null || !StringUtils.hasText(flagAct)) {
            return false;
        }
        
        Set<String> flagActs = getUserFlagActs(userType);
        return flagActs.contains(flagAct);
    }
    
    @Override
    public boolean hasMenuPermission(Integer userType, Integer fileId) {
        if (userType == null || fileId == null) {
            return false;
        }
        
        List<LxAdminFile> menus = getUserMenus(userType);
        return menus.stream()
                .anyMatch(menu -> menu.getId().equals(fileId));
    }
    
    @Override
    public Map<String, Object> getUserPermissions(Integer userType) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取用户组信息
        LxAdminGroup group = getGroupById(userType);
        if (group == null) {
            result.put("menus", Collections.emptyList());
            result.put("flags", Collections.emptyList());
            result.put("flagActs", Collections.emptySet());
            result.put("flagsByFile", Collections.emptyMap());
            return result;
        }
        
        // 解析允许的文件ID列表
        List<Integer> fileIds = parseIds(group.getAllowFile());
        List<Integer> flagIds = parseIds(group.getAllowFlag());
        
        // 获取菜单权限（与PHP逻辑一致：is_show=1 且 id in (allow_file)，排序：list_order asc, id desc）
        List<LxAdminFile> menus = fileIds.isEmpty() ? Collections.emptyList() : permissionMapper.selectFilesByIds(fileIds);
        result.put("menus", menus);
        
        // 按PHP逻辑：对每个file，查询其对应的flags（file_id=file.id 且 id in (allow_flag)）
        // 注意：PHP中查询flags时不过滤is_show，所有符合条件的flags都会被查询
        Map<Integer, List<LxAdminFlag>> flagsByFile = new HashMap<>();
        List<LxAdminFlag> allFlags = new ArrayList<>();
        
        if (!flagIds.isEmpty()) {
            for (LxAdminFile file : menus) {
                List<LxAdminFlag> fileFlags = permissionMapper.selectFlagsByFileIdAndFlagIds(file.getId(), flagIds);
                flagsByFile.put(file.getId(), fileFlags);
                allFlags.addAll(fileFlags);
            }
        }
        
        result.put("flags", allFlags);
        result.put("flagsByFile", flagsByFile);
        
        // 获取权限标识集合（用于前端快速判断）
        Set<String> flagActs = allFlags.stream()
                .map(LxAdminFlag::getFlagAct)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        result.put("flagActs", flagActs);
        
        return result;
    }
    
    /**
     * 解析ID字符串为ID列表
     * 格式：逗号分隔的ID字符串，如 "1,2,3,4"
     */
    private List<Integer> parseIds(String idsStr) {
        List<Integer> ids = new ArrayList<>();
        if (!StringUtils.hasText(idsStr) || "0".equals(idsStr.trim())) {
            return ids;
        }
        
        try {
            String[] idArray = idsStr.split(",");
            for (String idStr : idArray) {
                idStr = idStr.trim();
                if (StringUtils.hasText(idStr) && !"0".equals(idStr)) {
                    ids.add(Integer.parseInt(idStr));
                }
            }
        } catch (Exception e) {
            log.error("解析ID列表失败: {}", idsStr, e);
        }
        
        return ids;
    }
    
    @Override
    public List<LxAdminGroup> getAllGroups() {
        return permissionMapper.selectAllGroups();
    }
    
    @Override
    public List<LxAdminFile> getAllFiles() {
        return permissionMapper.selectAllFiles();
    }
    
    @Override
    public List<LxAdminFlag> getAllFlags() {
        return permissionMapper.selectAllFlags();
    }
    
    @Override
    public boolean saveGroup(LxAdminGroup group) {
        if (group.getId() != null && group.getId() > 0) {
            // 更新
            return permissionMapper.updateGroup(group) > 0;
        } else {
            // 新增
            return permissionMapper.insertGroup(group) > 0;
        }
    }
    
    @Override
    public boolean deleteGroup(Integer id) {
        return permissionMapper.deleteGroup(id) > 0;
    }
}

